package com.party.common.filter;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import org.springframework.http.MediaType;
import com.party.common.utils.StringUtils;

/**
 * Repeatable 过滤器
 * 
 * @author ruoyi
 */
public class RepeatableFilter implements Filter
{
    @Override
    public void init(FilterConfig filterConfig) throws ServletException
    {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException
    {
        // 定义一个ServletRequest类型的requestWrapper变量
        ServletRequest requestWrapper = null;
        // 判断request是否为HttpServletRequest类型，并且请求的Content-Type是否为application/json
        if (request instanceof HttpServletRequest
                && StringUtils.startsWithIgnoreCase(request.getContentType(), MediaType.APPLICATION_JSON_VALUE))
        {
            // 如果是，则创建一个RepeatedlyRequestWrapper对象，并将request和response作为参数传入
            requestWrapper = new RepeatedlyRequestWrapper((HttpServletRequest) request, response);
        }
        // 如果requestWrapper为空
        if (null == requestWrapper)
        {
            // 则直接调用chain.doFilter方法，将request和response作为参数传入
            chain.doFilter(request, response);
        }
        // 否则
        else
        {
            // 调用chain.doFilter方法，将requestWrapper和response作为参数传入
            chain.doFilter(requestWrapper, response);
        }
    }

    @Override
    public void destroy()
    {

    }
}
